package com.onlyxiahui.extend.spring.webflux.dispatcher.config;

import java.nio.charset.StandardCharsets;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;

import com.onlyxiahui.framework.action.dispatcher.extend.ActionResponse;
import com.onlyxiahui.framework.action.dispatcher.extend.ArgumentBox;
import com.onlyxiahui.framework.action.dispatcher.general.GeneralMessageHandler;
import com.onlyxiahui.framework.action.dispatcher.general.constant.ActionConstant;
import com.onlyxiahui.framework.action.dispatcher.general.util.ActionDispatcherJsonUtil;

import reactor.core.publisher.Mono;

/**
 * 
 * 
 * <br>
 * Date 2019-12-03 17:32:01<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */
@RestController
public class OnlyActionDispatcherPortal {

	@Autowired
	private GeneralMessageHandler generalMessageHandler;

	@ResponseBody
	public Object message(@RequestBody String body, ServerWebExchange exchange) {
		String path = exchange.getRequest().getPath().value();

		ArgumentBox argumentBox = generalMessageHandler.getArgumentBox();

		exchange.getAttributes().put(ActionConstant.ARGUMENT_BOX, argumentBox);
		exchange.getAttributes().put(ActionConstant.REQUEST_BODY_CACHE, body);
		ActionResponse actionResponse = new ActionResponse() {

			@Override
			public void write(Object data) {
				put(exchange, data);
			}
		};

		argumentBox.put(ActionResponse.class, actionResponse);
		argumentBox.put(ActionConstant.REQUEST_PATH, path);
		argumentBox.put(ServerWebExchange.class, exchange);
		// return actionDispatcher.action(request, actionResponse, argumentBox);
		return generalMessageHandler.doMessage(path, body, actionResponse, argumentBox);
	}

	private void put(ServerWebExchange exchange, Object resultData) {
		String json = ActionDispatcherJsonUtil.toJson(resultData);
		byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
		DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
		exchange.getResponse().setStatusCode(HttpStatus.UNPROCESSABLE_ENTITY);
		exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
		exchange.getResponse().writeWith(Mono.just(buffer));
	}
}
